import frappe


@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
def get_article(doctype, txt, searchfield, start, page_len, filters):
    if filters and filters.get("shoe_part"):
        shoe_part = filters.get("shoe_part")
    
    item = frappe.qb.DocType("Item")
    item_shoe_part = frappe.qb.DocType("Item Shoe Part")

    query = frappe.qb.from_(item
    ).select(
        item.name,
        item.item_name,
        item.item_name_ch
    ).where(
        item.item_group == "ARTICLE"
    )
    if txt:
        query = query.where(
            (
                (item.item_code.like(txt)) |
                (item.item_name.like(txt)) |
                item.item_name_ch.like(txt)
            )
        )
    if shoe_part:
        query = query.join(item_shoe_part
        ).on(item.name ==  item_shoe_part.parent
        ).where(
            item_shoe_part.shoe_part == shoe_part
        )
    data = query.run()

    return data

@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
def get_item_code(doctype, txt, searchfield, start, page_len, filters):   
    item = frappe.qb.DocType("Item")
    item_shoe_part = frappe.qb.DocType("Item Shoe Part")

    query = frappe.qb.from_(item
    ).select(
        item.name,
        item.item_name,
        item.item_name_ch
    )
    if txt:
        query = query.where(
            (
                (item.item_code.like(txt)) |
                (item.item_name.like(txt)) |
                item.item_name_ch.like(txt)
            )
        )

    if filters and filters.get("article"):
        article = filters.get("article")
        query = query.where(
            item.article == article
        )
    elif filters and filters.get("shoe_part"):
        shoe_part = filters.get("shoe_part")
        if shoe_part:
            query = query.join(item_shoe_part
            ).on(item.name ==  item_shoe_part.parent
            ).where(
                item_shoe_part.shoe_part == shoe_part
            )
    data = query.run()

    return data